package controllers

import (
	//	"encoding/json"
	"errors"
	"strconv"

	"gitee.com/lzqysoft/ilive/models"

	//	"fmt"
	"gitee.com/lzqysoft/ilive/libs"
	//	"gitee.com/lzqysoft/ilive/common/log"
	"strings"
	"time"

	//	"reflect"

	"github.com/astaxie/beego"
)

// oprations for User
type UserController struct {
	CommonController
}

func (c *UserController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Update", c.Update)
	c.Mapping("Delete", c.Delete)
	//	c.Mapping("Login", c.Login)
	//	c.Mapping("Logout", c.Logout)
	c.Mapping("Getme", c.Getme)
	c.Mapping("ChangePwd", c.ChangePwd)
	//	c.Mapping("UserStaticticsPage", c.UserStaticticsPage)
	//	c.Mapping("UserStatictics", c.UserStatictics)
	c.Mapping("GetAllOrgUsers", c.GetAllOrgUsers)
	//	c.Mapping("UserManager", c.UserManager)
	//	c.Mapping("GerUserByDept", c.GerUserByDept)
	c.Mapping("ManagerUser", c.ManagerUser)
	c.Mapping("GerUserByOrg", c.GerUserByOrg)

}

// @Title Post
// @Description create User
// @Param	body		body 	models.User	true		"body for User content"
// @Success 201 {int} models.User
// @Failure 403 body is empty
// @router / [post]
func (c *UserController) Post() {
	user := c.user
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	name := sdata["Name"].(string)
	//	判断账号是否重复
	if _, err := models.GetUserByUname(name); err == nil {
		c.RetError(ErrDupUser)
	}
	//	user对象
	var v models.User
	v.Name = name
	orgId, _ := sdata["Organization"].(string)
	oid, _ := strconv.ParseInt(orgId, 10, 64)
	org, _ := models.GetOrganizationById(oid)
	v.Organization = &org
	v.Remark, _ = sdata["Remark"].(string)
	vstatus, _ := sdata["Status"].(string)
	v.Status, _ = strconv.ParseInt(vstatus, 10, 64)
	pwd := beego.AppConfig.String("defaultsPwd")
	v.Pwd = libs.EncodeUserPwd(name, pwd)
	v.Isdelete = 0
	v.Ctime = time.Now()
	v.Creater = user.Name
	v.Utime = v.Ctime
	v.Updater = v.Creater
	//创建userrole对象
	//	var ur models.UserRole
	roleId, _ := sdata["RoleId"].(string)
	rid, _ := strconv.ParseInt(roleId, 10, 64)
	role, _ := models.GetRoleById(rid)
	//创建userdept对象
	dept, err := models.GetDeptByName(v.Organization.Name, v.Organization.Id)
	beego.Debug(roleId, dept)
	if user.Organization.Id == oid {
		dept = *user.Dept[0]
	}
	//创建userprof对象
	var up models.Userprof
	up.Type = 0
	up.Sex = 0
	up.Phone = ""
	up.Contact = ""
	up.Expert = ""
	up.Title = sdata["Pname"].(string)
	up.Job = ""
	up.Point = 0
	up.Photo = "default.jpg"
	up.Email = ""
	up.Logintime = time.Now()
	up.Loginip = ""
	up.Logincount = 0
	up.Remark = ""
	up.Isdelete = 0
	up.Ctime = time.Now()
	up.Creater = user.Name
	up.Utime = up.Ctime
	up.Updater = up.Creater

	beego.Debug(up.Title)
	id, err := models.CreateUser(&v, &up, role.Id, dept.Id)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	c.Dlog("添加了用户", id)
	c.RetSuccess("ok")
}

// @Title Get
// @Description get User by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.User
// @Failure 403 :id is empty
// @router /:id [get]
func (c *UserController) GetOne() {
	id, _ := c.GetInt64(":id")
	v, err := models.GetUserById(id)
	if err != nil {
		c.RetError(ErrNoData)
	}
	c.RetSuccess(v)
}

// @Title Get All
// @Description get User
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.User
// @Failure 403
// @router / [get]
func (c *UserController) GetAll() {
	var fields []string
	var sortby []string
	var order []string
	query := make(map[string]interface{})
	var limit int64 = -1
	var offset int64 = 0

	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}
	//	roleid := c.GetSession("roleinfo").(models.Role).Id

	l, _, err := models.GetAllUser(query, fields, sortby, order, offset, limit)
	if err != nil {
		beego.Error("err is :", err)
		c.RetError(ErrDatabase)
	}
	beego.Error("err is :", err)
	c.RetSuccess(l)

}

// @Title Update
// @Description update the User
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.User	true		"body for User content"
// @Success 200 {object} models.User
// @Failure 403 :id is not int
// @router /Update [post]
func (c *UserController) Update() {
	user := c.user
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	sid := sdata["Id"].(string)
	id, _ := strconv.ParseInt(sid, 10, 64)
	v, err := models.GetUserById(id)
	if err != nil {
		c.RetError(ErrInputData)
	}
	//	orgId, _ := sdata["OrgId"].(string)
	//	oid, _ = strconv.ParseInt(orgId, 10, 64)
	//	org,_:=models.GetOrganizationById(oid)
	//	_, err = models.GetOrganizationById(v.Organization.Id)
	//	if err != nil {
	//		c.RetError(ErrInputData)
	//	}
	v.Remark, _ = sdata["Remark"].(string)
	vstatus, _ := sdata["Status"].(string)
	v.Status, _ = strconv.ParseInt(vstatus, 10, 64)
	v.Updater = user.Name
	v.Utime = time.Now()
	//	ur, err := models.GetUserRoleByUserId(id)
	//	for k, ss := range sdata {
	//		beego.Debug(k, reflect.TypeOf(ss))
	//	}
	//	beego.Debug(ur, err, id)
	//	if err != nil {
	//		c.RetError(ErrInputData)
	//	}
	roleId, _ := sdata["RoleId"].(string)
	rid, _ := strconv.ParseInt(roleId, 10, 64)
	//	role, _ := models.GetRoleById(rid)

	//	v.Role = role

	up, err := models.GetUserprofById(id)
	if err != nil {
		c.RetError(ErrInputData)
	}
	up.Title = sdata["Pname"].(string)
	up.Updater = user.Name
	up.Utime = time.Now()
	beego.Debug(rid)
	err = models.UpdateUser(v, up, rid)
	if err != nil {
		c.RetError(ErrInvalidUser)
	}
	c.Dlog("修改用户", id)
	c.RetSuccess("ok")
}

// @Title Delete
// @Description delete the User
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /Delete [post]
func (c *UserController) Delete() {
	user := c.user
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	sid := sdata["Id"].(string)
	id, err := strconv.ParseInt(sid, 10, 64)
	err = models.SoftDeleteUser(id, user.Name)
	if err != nil {
		c.RetError(ErrDatabase)
	}
	c.Dlog("删除了用户", id)
	c.RetSuccess(id)
}

// @Title 获取用户自身数据
// @Description User Getme
// @Success 200
// @Failure 403 :
// @router /Getme [get]
func (this *UserController) Getme() {
	user := this.user
	// beego.Debug("getme ...............")
	jdata := make(map[string]interface{})
	//	org, err := models.GetOrganizationById(user.Organization.Id)
	//	if err != nil {
	//		this.RetError(ErrNoUser)
	//	}
	//	userprof, err := models.GetUserprofById(user.Id)
	//	if err != nil {
	//		this.RetError(ErrNoUser)
	//	}
	//	role, err := models.GetRoleByUserId(user.Id)
	//	if err != nil {
	//		this.RetError(ErrNoUser)
	//	}
	accessList := models.GetAccessTreeByRoleId(user.Role[0].Id)

	jdata["userinfo"] = user
	jdata["userprof"] = user.Userprof
	jdata["org"] = user.Organization
	jdata["dept"] = user.Dept[0]
	jdata["role"] = user.Role[0]
	jdata["accesslist"] = accessList
	this.Dlog("登录系统，用户名为：", user.Id, 2)
	this.RetSuccess(jdata)

}

// @Title ChangePwd
// @Description ChangePwd
// @Success 200
// @Failure 403 :
// @router /ChangePwd [post]
func (this *UserController) ChangePwd() {
	//	user := this.user
	rdata, err := this.AesDecode(this.GetString("tdata"))
	if err != nil {
		this.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	oldPwd := sdata["oldPwd"].(string)
	newPwd := sdata["newPwd"].(string)
	repeatPwd := sdata["repeatPwd"].(string)
	beego.Debug(this.user.Name, oldPwd)
	if newPwd != repeatPwd {
		this.RetError(ErrInputData)
	}
	user, err := models.CheckLogin(this.user.Name, oldPwd)
	if err != nil {
		beego.Debug(err)
		this.RetError(ErrInputData)
	}
	p := libs.EncodeUserPwd(user.Name, newPwd)
	user.Pwd = p
	err = models.UpdateUserById(&user)
	if err != nil {
		this.RetError(ErrDatabase)
	}
	this.Dlog("修改密码", user.Id)
	this.RetSuccess(user.Id)
}

// @Title DeleteUsers
// @Description DeleteUsers
// @Success 200
// @Failure 403 :
// @router /DeleteUsers [post]
func (this *UserController) DeleteUsers() {
	user := this.user
	rdata, err := this.AesDecode(this.GetString("tdata"))
	if err != nil {
		this.RetError(ErrToken)
	}
	sdata, _ := rdata.([]interface{})
	for _, value := range sdata {
		eid := value.(string)
		id, _ := strconv.ParseInt(eid, 10, 64)
		err := models.SoftDeleteUser(id, user.Name)
		if err != nil {
			this.RetError(ErrDatabase)
		}
		this.Dlog("删除了角色", id)
	}
	this.RetSuccess(sdata)
}

// @Title ResetPwd
// @Description ResetPwd
// @Success 200
// @Failure 403 :
// @router /ResetPwd [post]
func (this *UserController) ResetPwd() {
	user := this.user
	rdata, err := this.AesDecode(this.GetString("tdata"))
	if err != nil {
		this.RetError(ErrToken)
	}
	sdata, _ := rdata.([]interface{})
	for _, value := range sdata {
		eid := value.(string)
		id, _ := strconv.ParseInt(eid, 10, 64)
		v, err := models.GetUserById(id)
		v.Pwd = libs.EncodeUserPwd(v.Name, beego.AppConfig.String("defaultsPwd"))
		v.Updater = user.Name
		v.Utime = time.Now()
		err = models.UpdateUserById(v)
		if err != nil {
			this.RetError(ErrDatabase)
		}
		this.Dlog("重置了用户密码", id)
	}
	this.RetSuccess("ok")
}

// @Title GetAllOrgUsers
// @Description 获取单位用户
// @Success 200
// @Failure 403 :
// @router /GetAllOrgUsers [get]
func (c *UserController) GetAllOrgUsers() {
	user := c.user
	//	rdata, err := c.AesDecode(c.GetString("tdata"))
	//	if err != nil {
	//		c.RetError(ErrToken)
	//	}
	var fields []string
	var sortby []string
	var order []string
	var limit int64 = -1
	var offset int64 = 0
	query := make(map[string]interface{})
	tabledata := make(map[string]interface{})
	//	sdata, _ := rdata.(map[string]interface{})
	//	//	orgId := user.Organization.Id
	//	ipage, _ := sdata["page"].(string)
	//	page, _ := strconv.ParseInt(ipage, 10, 64)
	//	ipagesize, _ := sdata["pagesize"].(string)
	//	pagesize, _ := strconv.ParseInt(ipagesize, 10, 64)
	//	if page <= 1 {
	//		offset = 0
	//	} else {
	//		offset = (page - 1) * pagesize
	//	}
	//	limit = pagesize
	beego.Debug(user.Role[0].Type, user.Role[0].Name)
	switch user.Role[0].Type {
	case 1:
		query["Organization"] = strconv.FormatInt(user.Organization.Id, 10)
	case 2:
		ids := models.GetDeptChildrenStr(user.Dept[0].Id)
		query["Dept__Dept__Id__in"] = *ids
	}
	//	query["Organization"] = strconv.FormatInt(orgId, 10)
	l, count, err := models.GetAllUser(query, fields, sortby, order, offset, limit)
	if err != nil {
		beego.Error("err is :", err)
		c.RetError(ErrDatabase)
	}
	//	beego.Error("count is :", count, l)
	tabledata["total"] = count
	tabledata["tabledata"] = l
	c.RetSuccess(l)

}

// @Title GerUserByOrg
// @Description 根据单位获取人员穿梭表
// @Success 200
// @Failure 403 :
// @router /GerUserByOrg [get]
func (c *UserController) GerUserByOrg() {
	user := c.user
	//	deptId, _ := c.GetInt64("DeptId")
	if datas, err := models.GetUserByOrg(user.Organization.Id); err == nil {
		c.RetSuccess(datas)
	}
	c.RetError(ErrNoData)
}

// @Title ManagerUser
// @Description 分配部门人员
// @Success 200
// @Failure 403 :
// @router /ManagerUser [post]
func (c *UserController) ManagerUser() {
	deptId, _ := c.GetInt64("DeptId")
	todos := c.GetStrings("todo[]")
	dones := c.GetStrings("done[]")
	if len(todos) > 0 {
		if err := models.SetUserDept(0, todos); err == nil {
			if len(dones) > 0 {
				if err := models.SetUserDept(deptId, dones); err == nil {
					c.Data["json"] = "ok"
					c.Dlog("分配部门", deptId)
				} else {
					c.Data["json"] = err.Error()
				}
			}
		} else {
			c.Data["json"] = err.Error()
		}
	} else {
		if err := models.SetUserDept(deptId, dones); err == nil {
			c.Data["json"] = "ok"
			c.Dlog("分配部门", deptId)
		} else {
			c.Data["json"] = err.Error()
		}
	}

	c.ServeJSON()
}
